import axios from 'axios'

let BASEURL = `` // 配置基本api
let shopId = window.location.pathname.split('/')[1]
axios.defaults.timeout = 100000 // 请求超时时间
export default function (type = 'get', url, data, formFile = false) {
  return new Promise((resolve, reject) => {
    let headers = { // 请求头
      'accessToken': window.localStorage.accessToken || '',
      'Content-Type': formFile ? 'multipart/form-data;charset=UTF-8' : 'application/json;charset=UTF-8'
    }
    type = type.toLowerCase()
    let config = {
      method: type,
      headers,
      url: BASEURL + url
    }
    if (type === 'get') {
      config.params = data
    } else if (type === 'post') {
      config.data = data
    }

    // 添加响应拦截器
    axios.interceptors.response.use(function (response) { // 响应数据处理
      if (!response) return reject(response)
      let data = response.data
      switch (Number(data.code)) {
        case 100001: // 登录超时
          window.localStorage.accessToken = ''
          window.$message.closeAll()
          window.$message({
            message: '登录超时',
            type: 'warning',
            duration: 1000,
            onClose: () => {
              window.location.href = `/${shopId}/login`
            }
          })
          break
        case 200: // 成功
          break
        default:
          window.$message.closeAll()
          window.$message({ message: data.msg, type: 'warning' })
          break
      }
      return response
    }, function (error) { // 响应错误处理
      // window.$toast.clear()
      // window.$dialog.alert({message: '网络错误'})
      return reject(error)
    })
    axios(config).then(res => {
      if (Number(res.data.code) === 200) {
        resolve(res.data)
      } else {
        reject(res.data)
      }
    }).catch(err => {
      reject(err)
    })
  })
}
